// pages/search/search.js
Page({
  data: {
      history: [],
      hot: ['口碑粉水', '大眼精华', '菁纯眼霜','菁纯宝石唇膏'],
      result: [
          {
              id: 1,
              url: '/pages/details1/details1',
              thumb:  '/images/z1.png',
              title: '口碑粉水',
              price: 420
          },
          {
              id: 2,
              url: '/pages/details2/details2',
              thumb: '/images/z2.png',
              title: '极光水',
              price: 780
          }
      ],
      showKeywords: false,
      keywords: ['菁纯眼霜','菁纯小姐唇膏', '持妆粉底液', '极光水', ],
      value: '',
      showResult: false,
  },
  cancelSearch() {
      this.setData({
          showResult: false,
          showKeywords: false,
          value: ''
      })
  },
  searchInput(e) {
      if(!e.detail.value){
          this.setData({
              showKeywords: false
          })
      }else{
          if(!this.data.showKeywords){
              timeId && clearTimeout(timeId);
              timeId = setTimeout(() => {
                  this.setData({
                      showKeywords: true
                  })
              }, 1000)
          }
      }
  },
  keywordHandle(e) {
      const text = e.target.dataset.text;
      this.setData({
          value: text,
          showKeywords: false,
          showResult: true
      })
      this.historyHandle(text);
  },
  historyHandle(value) {
      let history = this.data.history;
      const idx = history.indexOf(value);
      if (idx === -1) {
          // 搜索记录只保留8个
          if (history.length > 4) {
              history.pop();
          }
      } else {
          history.splice(idx, 1);
      }
      history.unshift(value);
      wx.setStorageSync('history', JSON.stringify(history));
      this.setData({
          history
      });
  },
  onLoad() {
      const history = wx.getStorageSync('history');
      if (history) {
          this.setData({
              history: JSON.parse(history)
          })
          console.log(this.data.history);
      }
  }
})